package services

import (
	"fmt"
	"github.com/goravel/framework/facades"
	"goravel/app/models"
	"goravel/app/types"
)

const (
	CategoryMaxDeep     = 4
	CategoryCacheKeyAll = "category:all"
)

type CategoryService struct {
	DBService
	Biz string
}

func NewCategoryService(biz string) *CategoryService {
	return &CategoryService{
		Biz: biz,
	}
}

func (s *CategoryService) CacheAll() {
	all, err := s.GetChildren(0, 3)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", all)
	err = facades.Cache().Put(CategoryCacheKeyAll+s.Biz, all, 0)
	if err != nil {
		panic(err)
	}
}

func (s *CategoryService) GetChildren(parentId int, deep int) ([]types.CategoryResp, error) {
	var dao []models.Category
	var vos []types.CategoryResp
	var err error
	err = facades.Orm().Query().Model(&dao).Where("biz", s.Biz).Where("parent_id", parentId).Find(&vos)
	if err != nil {
		return nil, err
	}
	if deep > CategoryMaxDeep {
		deep = CategoryMaxDeep
	}
	if deep <= 0 {
		return vos, nil
	}
	if len(vos) == 0 {
		return vos, nil
	}
	for index, vo := range vos {
		children, err := s.GetChildren(int(vo.Id), deep-1)
		if err != nil {
			vos[index].Children = nil
		}
		vos[index].Children = children
	}
	return vos, nil
}
